#!/usr/bin/python
# coding:utf-8

from flask import request, url_for
from flask_restplus import Namespace, Resource, fields

import dbpool

CATS = [
    {'id': '1', 'name': 'Felix'},
    {'id': '2', 'name': 'Jack'},
]

ns = Namespace('cats', description='Cats Rest API')

cat = ns.model('Cat', {
    'id': fields.String(required=True, description='The cat identifier'),
    'name': fields.String(required=True, description='The cat name'),
})


@ns.route('/')
class CatList(Resource):
    @ns.marshal_list_with(cat)
    def get(self):
        print(url_for('rest.cat', id=1))
        # # List all cats
        return CATS

    @ns.doc(security='apikey')
    @ns.expect(cat)
    @ns.marshal_with(cat, code=201, description='Object created')
    def post(self):
        # Create a new user
        u = request.json
        idx = len(CATS)
        u['id'] = str(idx)
        CATS.append(u)
        return u, 201


@ns.route('/<id>', endpoint='cat')
@ns.doc(description='这是cat的API')
@ns.param('id', 'The cat\'s ID')
@ns.response(404, 'Cat not found')
class Cat(Resource):
    @ns.marshal_with(cat, description='成功')
    @ns.doc(description='读取')
    def get(self, id):

        with dbpool.create_cursor() as (conn, cursor):
            pass

        # Fetch a cat given its identifier
        for c in CATS:
            if c['id'] == id:
                return c
        ns.abort(404)

    @ns.deprecated
    @ns.marshal_with(cat)
    @ns.doc(description='更新')
    @ns.expect(cat, validate=True)
    def put(self, id):
        u = self.get(id)
        n = request.json
        u.update(n)
        return u
